#include "ReplaceTextDialog.h"

ReplaceTextDialog::ReplaceTextDialog(QWidget* parent):QDialog(parent)
{
	ui.setupUi(this);
	TextEdit = NULL;
	IsDoReplaceAll = false;
	connect(ui.ReplaceBox, SIGNAL(clicked()), this, SLOT(DoReplace()));
	connect(ui.ReplaceAllBox, SIGNAL(clicked()), this, SLOT(DoReplaceAll()));
}

ReplaceTextDialog::~ReplaceTextDialog(void)
{}

void ReplaceTextDialog::SetTextEdit(QsciScintilla* TextEdit)
{
	this->TextEdit = TextEdit;
}

void ReplaceTextDialog::DoReplaceAll(void)
{
	IsDoReplaceAll = true;
	DoReplace();
}

void ReplaceTextDialog::DoReplace(void)
{
	QString FindText = ui.FindText->currentText();
	QString ReplaceText = ui.ReplaceText->currentText();
	if(FindText.isEmpty())
	{
		QMessageBox::warning(this, SoftwareName,
                             tr("Text to Find is empty"));
                return ;
	}
	ui.FindText->addItem(FindText);
	ui.FindText->setEditText("");
	ui.ReplaceText->addItem(ReplaceText);
	ui.ReplaceText->setEditText("");

    Regex = ui.Regex->isChecked();
    CaseSens = ui.CaseSensitive->isChecked();
    WholeWord = ui.WholeWords->isChecked();
    Forward = !ui.FindBackwards->isChecked();
    bool result = TextEdit->findFirst(FindText, Regex, CaseSens, WholeWord, false, Forward);
	if(result)
	{
		TextEdit->replace(ReplaceText);
		if(IsDoReplaceAll)
		{
			result = TextEdit->findNext();
			while(result)
			{
				TextEdit->replace(ReplaceText);
				result = TextEdit->findNext();
			}
		}
		IsDoReplaceAll = false;
	}
	else
	{
		QMessageBox::warning(this,SoftwareName,tr("Not find match text "));
		return ;
	}
	close();
}
